package com.chinasofti.project.web;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chinasofti.project.dal.model.BzUser;
import com.chinasofti.project.service.order.OrderService;
import com.chinasofti.project.service.user.UserService;
import com.chinasofti.project.web.common.ControllerBase;
import com.chinasofti.project.web.form.OrderForm;
import com.chinasofti.project.web.form.ShopcartForm;
import com.chinasofti.project.web.info.OrderResult;

@Controller
public class OrderController extends ControllerBase {

	@Autowired
	private OrderService orderService;

	@Autowired
	private UserService userService;

	@RequestMapping("updateOrder")
	public String completePay(int orderId, String orderCurrAddress, BigDecimal orderShouldPayment,
			BigDecimal userBalance, int userId) {
		OrderForm orderForm = new OrderForm();
		orderForm.setOrderId(orderId);
		orderForm.setOrderState("已付款");
		orderForm.setOrderCurrAddress(orderCurrAddress);
		orderForm.setOrderShouldPayment(orderShouldPayment);
		orderForm.setOrderRealPayment(orderShouldPayment);
		orderForm.setOrderPaymentTime(new Date());
		orderService.updateOrder(orderForm);
		BigDecimal nowBalance = userBalance.subtract(orderShouldPayment);
		BzUser user = new BzUser();
		user.setUserId(userId);
		user.setUserBalance(nowBalance);
		userService.updateUserBalance(user);

		return "successPay";
	}

	@RequestMapping("toCreateOrder")
	private String toCreateOrder(ShopcartForm shopcartForm, HttpSession session, ModelMap mm) {
		int userId = (int) session.getAttribute("userId");
		mm.put("userId", userId);
		if (shopcartForm.getProductId().size() == 0 || shopcartForm.getScProductNum().size() == 0) {
			return "toBreezeShopcart";
		}
		OrderResult orderResult = orderService.createOrder(shopcartForm.getProductId(), shopcartForm.getScProductNum(),
				userId);
		mm.put("orderResult", orderResult);

		return "pay";
	}
}
